<template>
  <view class="content">
    <view class="text-area">
      <button @click="readBLECharacteristicValue">读取数据</button>
      <button @click="writeBLECharacteristicValue('hfk中g')">发送数据</button>
      <button @click="Search">搜索蓝牙</button>
    </view>
    <scroll-view scroll-y class="box">
      <view class="item" v-for="item in devicesList">
        <view>
          <text>id:{{ item.deviceId }}</text>
        </view>
        <view>
          <text>name:{{ item.name }}</text>
          <button @click="ConnectByID(item)">连接</button>
        </view>
        <view>{{data}}</view>
      </view>
    </scroll-view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      title: 'Hello',
      deviceId: '',
      serviceId: '',
      characteristicId: '',
      connectedDeviceId: '',
      devicesList: [],
      data: ''
    }
  },

  methods: {
    Search() {
      var that = this;
      //console.log("search:", that.searching);
      if (!that.searching) {
        //关闭现有的蓝牙连接
        uni.closeBluetoothAdapter({
          complete: function(res) {
            console.log("关闭蓝牙模块-----------------------------------------");
            console.log(res);
            //打开蓝牙适配
            uni.openBluetoothAdapter({
              success: function(res) {
                uni.getBluetoothAdapterState({
                  success: function(res) {
                  },
                });

                //开始搜索蓝牙设备
                uni.startBluetoothDevicesDiscovery({
                  allowDuplicatesKey: false,
                  success: function(res) {
                    that.onBluetoothDeviceFound();
                    that.searching = true;
                    that.devicesList = [];
                  },
                });
              },
              fail: function(res) {
                console.log("############");
                console.log(res);
                setTimeout(() => {
                  uni.showModal({
                    title: "温馨提示",
                    content: "蓝牙未打开，请打开后再连接",
                    showCancel: false,
                    confirmColor: "#008fd6",
                  });
                  that.isSearch = false;
                }, 1000);
              },
            });
          },
        });
      } else {
        uni.stopBluetoothDevicesDiscovery({
          success: function(res) {
            console.log("停止搜索设备-----------------------------------------");
            console.log(res);
            that.searching = false;
          },
        });
      }
    },
    ConnectByID(item) {
      var that = this;
      console.log(item);
      that.connectedDeviceId = item.deviceId;
      uni.setStorageSync('pageName', item.name);
      uni.setStorageSync('connectedDeviceId', that.connectedDeviceId);
      uni.showLoading({
        title: '正在连接设备...',
      });

      uni.createBLEConnection({
        deviceId: item.deviceId,
        success(res) {
          uni.hideLoading()
          uni.showToast({
            title: '连接成功',
            duration: 2000,
            icon: "none"
          });
          // that.open()
          console.log("已连接设备----------------------------------------");
          that.getBLEDeviceServices(); //获取特征值

        },
        fail(res) {
          console.log(res)
          uni.hideLoading()
          uni.showModal({
            title: '提示',
            content: '连接失败',
            showCancel: false
          })
        }
      })
      // }
    },
    //获取蓝牙设备的服务uuid    //服务uuid可能有多个
    getBLEDeviceServices() {
      var that = this;
      setTimeout(() => {
        //获取数据可能会有延迟
        uni.getBLEDeviceServices({
          deviceId: that.connectedDeviceId,
          success: function(res) {
            console.log(
                "获取蓝牙设备的服务uuid:" + JSON.stringify(res.services)
            );
            that.services = res.services;
            that.serviceId = res.services[2].uuid;
            that.deviceId = that.connectedDeviceId;
            uni.setStorageSync("serviceId", that.serviceId);
            that.getBLEDeviceCharacteristics();
          },
          fail(res) {
            console.log(res);
          },
        });
      }, 1000);
    },
    // 根据服务uuid获取蓝牙特征值开始监听写入和接收
    getBLEDeviceCharacteristics() {
      let that = this;
      uni.getBLEDeviceCharacteristics({
        deviceId: that.connectedDeviceId,
        serviceId: that.serviceId,
        success: function(res) {
          console.log(
              "获取蓝牙设备的特征" + JSON.stringify(res.characteristics)
          );
          for (var i = 0; i < res.characteristics.length; i++) {
            if (res.characteristics[i].properties.notify === true) {
              that.characteristics = res.characteristics[i];
              that.characteristicId = res.characteristics[i].uuid;
            }

            if (res.characteristics[i].properties.write === true) {
              that.characteristics = res.characteristics[i];
              that.writeId = res.characteristics[i].uuid;
            }
          }
          uni.setStorageSync("characteristicId", that.characteristicId);
          uni.setStorageSync("writeId", that.writeId);
          that.notifyBLECharacteristicValueChange(); //7.0,开始侦听数据
        },
      });
    },


    notifyBLECharacteristicValueChange() {
      var that = this;
      uni.notifyBLECharacteristicValueChange({

        state: true,
        deviceId: that.deviceId,
        serviceId: that.serviceId,
        characteristicId: that.characteristicId,

        success: function(res) {
          console.log("启用notify成功");
          that.onBLECharacteristicValueChange();
        },
        fail: function(res) {
          console.log("启用notify失败");
        },
      });
    },
    ab2hex(buffer) {
      const hexArr = Array.prototype.map.call(
          new Uint8Array(buffer),
          function(bit) {
            return ('00' + bit.toString(16)).slice(-2)
          }
      )
      return '%' + hexArr.join('%')
    },
    //设备返回数据的接收
    onBLECharacteristicValueChange() {
      var that = this;
      console.log("开启数据监听");
      uni.onBLECharacteristicValueChange((res) => {
        console.log("处理数据1：" + (Buffer)(res.value)); //重点在这里直接 (Buffer)就可以用了。网上还要转码。
      });
    },

    //监听寻找到新设备的事件
    //平时有数据来也没反应，执行一次readBLECharacteristicValue才反应一次
    onBluetoothDeviceFound() {
      var that = this;
      console.log("打开设备监听");
      uni.onBluetoothDeviceFound(function(devices) {
        var reg = new RegExp(/[^\s]+/g);
        if (devices.devices) {
          if (devices.devices[0].name.match(reg)) {
            if (devices.devices[0].localName.includes("ESP32")) {
              console.log(devices.devices);
              //在app显示
              that.devicesList.push(devices.devices[0]);
              console.log("发现ESP32");
              //连接蓝牙设备
              setTimeout(ConnectByID(devices.devices[0]), 1000);
            }
          }
        }
      });
    },
    onBLEConnectionStateChange() {
      var that = this;
      uni.onBLEConnectionStateChange(function(res) {
        that.connected = res.connected;
        if (!that.connected) {
          console.log("蓝牙已断开");
          uni.createBLEConnection({
            // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
            deviceId: that.connectedDeviceId,
            success(res) {
              that.getBLEDeviceServices();
              //获取该设备地址
              console.log("蓝牙重新连接" + JSON.stringify(res));
            },
            fail(res) {
              console.log("蓝牙重新连接失败" + JSON.stringify(res));
            },
          });
        } else {
          console.log("蓝牙连接成功");
        }
      });
    },
    readBLECharacteristicValue() {
      let _this = this;
      plus.bluetooth.readBLECharacteristicValue({
        // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
        deviceId: "84:CC:A8:54:17:F2",
        // 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
        serviceId: "4fafc201-1fb5-459e-8fcc-c5c9c331914b",
        // 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
        characteristicId: "beb5483e-36e1-4688-b7f5-ea07361b26a8",
        success: res => {
          uni.onBLECharacteristicValueChange(function(res) {
            console.log("接收到蓝牙数据:" + (Buffer)(res.value))
            _this.data = (Buffer)(res.value)
          });
        },
        fail: res => {
    
        },
      });
    },

    // 写入低功耗蓝牙设备的特征值
    writeBLECharacteristicValue(value) {
      const _this = this;
      _this.buffer = new Buffer(value); //UTF-8字符
      uni.writeBLECharacteristicValue({
        deviceId: _this.deviceId,
        serviceId: _this.serviceId,
        characteristicId: _this.characteristicId,
        value: 12.2,
        writeType: 'writeNoResponse',
        success: function(e) {
        },
        fail: function(e) {
        }
      });
    },
    //断开蓝牙连接
    closeBLEConnection(deviceId, index) {
      const _this = this;
      plus.bluetooth.closeBLEConnection({
        deviceId: deviceId,
        success: res => {
          console.log('断开蓝牙连接');
          if (index >= 0) {
            _this.isLink.splice(index, 1, 4);
          }
          mHelper.toast('已断开连接！');
        }
      });
    },
  },

  onLoad() {
    let hexString = "68656c6c6f";
    let str = "";
    for (let i = 0; i < hexString.length; i += 2) {
      let hex = hexString.substr(i, 2);
      str += String.fromCharCode(parseInt(hex, 16));
    }
    this.Search();
  },
}
</script>

<style>
.content {
  padding-top: 120rpx;
}

.box {
  width: 100%;
  height: 800 rpx;
  box-sizing: border-box;
  margin-bottom: 20 rpx;
  border: 2px solid dodgerblue;
}

.item {
  box-sizing: border-box;
  padding: 10 rpx;
  border-bottom: 1px solid #ccc;
}

button {
  margin-bottom: 20 rpx;
}
</style>